package com.app.demo.controller;

import com.app.core.mvc.result.Result;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author qiangt
 * @version 1.0
 * @description: 测试限流
 * @date 2023/10/14 8:11
 */
@RestController
@RequestMapping("/limiter")
@RequiredArgsConstructor
public class LimiterController {

    private final RedissonClient redissonClient;

    @RequestMapping("/testLimiter")
    public Result<Void> testLimiter(@RequestParam long rate, @RequestParam long rateInterval) {
        RRateLimiter limiter = getRateLimiter("testLimiter", rate, rateInterval);
        if (tryAcquire(limiter, 3)) {
            return Result.success();
        } else {
            return Result.fail();
        }
    }

    public RRateLimiter getRateLimiter(String key, long rate, long rateInterval) {
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        rateLimiter.trySetRate(RateType.OVERALL, rate, rateInterval, RateIntervalUnit.SECONDS);
        return rateLimiter;
    }

    public boolean tryAcquire(RRateLimiter rateLimiter, long timeout) {
        return rateLimiter.tryAcquire(1, timeout, TimeUnit.SECONDS);
    }
}
